package Triangulation.oldMinimalityMetrics;

import static tools.Tool.*;
import datatypes.Edge;
import datatypes.Triangle;
import datatypes.Vertex;

public class OldBaseToHeightRatioMetric extends OldAbstractMinimalityMetric {
	
	/**
	 * The longer length divided by the shorter length.
	 * Hence, the value is >= 1.0.
	 * @param length1
	 * @param length2
	 * @return
	 */
	private double ratio (double length1, double length2) {
		return length1 > length2 ? length1 / length2 : length2 / length1;
	}

	
	@Override
	public boolean edgeIsLocallyMinimal(Edge sharedEdge, Triangle t1, Triangle t2) {
		if ( ! quadIsConvex(t1, t2, sharedEdge)) {
			// If quad is NOT convex, then sharedEdge is locally minimal.
			// See "A Large Subgraph of the Minimum Weight Triangulation" 
			// p.291, 1.3
			return true;
		}
		Vertex t1p = t1.getVertexNotOnEdge(sharedEdge);
		Vertex t2p = t2.getVertexNotOnEdge(sharedEdge);
		double sharedEdgeLength = sharedEdge.getLength();
		
		// summing up the ratios of sharedEdge.length and height of 
		// both triangles:
		double ratioSharedEdge = ratio(sharedEdgeLength, t1.height(sharedEdge));
		ratioSharedEdge += ratio(sharedEdgeLength, t2.height(sharedEdge));
		
		// same for the other diagonal of the quadrilateral:
		Edge perpendicularEdge = new Edge(t1p, t2p);
		double perpendicularEdgeLength = perpendicularEdge.getLength();
		
		Triangle t1Alt;
		double ratioPerpendicularEdge = 0.0;
		try {
			t1Alt = new Triangle(perpendicularEdge, new Edge(perpendicularEdge.getVertex1(), sharedEdge.getVertex1()), new Edge(perpendicularEdge.getVertex2(), sharedEdge.getVertex1()), true);
			Triangle t2Alt = new Triangle(perpendicularEdge, new Edge(perpendicularEdge.getVertex1(), sharedEdge.getVertex2()), new Edge(perpendicularEdge.getVertex2(), sharedEdge.getVertex2()), true);
			
			ratioPerpendicularEdge = ratio(perpendicularEdgeLength, t1Alt.height(perpendicularEdge));
			ratioPerpendicularEdge += ratio(perpendicularEdgeLength, t2Alt.height(perpendicularEdge));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		// the sharedEdge is locally minimal if its sum of the two ratios is
		// less than the sum of the ratios of the flipped edge.
		return ratioSharedEdge <= ratioPerpendicularEdge;
	}


	@Override
	public String getName() {
		return "best base-height ratio";
	}

}
